<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Victor
 * Date: 28.11.11
 * Time: 23:41
 * To change this template use File | Settings | File Templates.
 */

class Auth_Auth
{
    /**
     * @var DataModule
     */
    private $dataModule;

    public function setDataModule(DataModule $dataModule)
    {
        $this->dataModule = $dataModule;

    }


    public function login($login, $password)
    {
        $this->checkUser($password, $login);


    }

    /**
     * @param $password
     * @param $login
     * @return bool
     */
    public function checkUser($password, $login)
    {
        $pass = md5(md5($password));
        $pdo = $this->dataModule->getConnection();
        $sql = "SELECT * from `dzundza_account` where login = :login and password = :password";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':login', $login, PDO::PARAM_STR);
        $stn->bindParam(':password', $pass, PDO::PARAM_STR);
        $stn->execute();

        $result = $stn->fetchAll(PDO::FETCH_ASSOC);
        if (count($result) > 0) {
            return true;
        } else {
            return false;
        }
    }

    public function logOut($username)
    {
    }

    /**
     * @param $username
     * @return Array
     */
    public function getUserPrivileges($username)
    {
    }

    public function clearSession($login)
    {
        session_name("sess_" . $login);
        session_start();
        session_unset();
        session_destroy();
        $this->insertHashToDB($login, NULL);

    }

    public function isAuthorize($login, $password)
    {
        if (empty($login) && empty($password)) return; else
        {
            if (!isset($_COOKIE['hash']) && empty($_COOKIE['hash'])) {
                //echo "user not authorized</br>";
                //var_dump(!isset($_COOKIE['hash']));
                //var_dump(empty($_COOKIE['hash']));
                $this->authorizeUser($login, $password);
            } else {
                $hash = $_COOKIE['hash'];
                $checked = $this->checkHash($login, $hash);

                //var_dump($checked);

                if (!$checked) {
                    //echo "user $login not authorized</br>";
                    $this->authorizeUser($login, $password);

                } else {
                    //echo "user $login  authorized</br>";
                    //echo "with id:$hash</br>";
                }
            }

        }

    }

    public function  authorizeUser($login, $password)
    {
        $sid = md5(crypt($password . md5($login . time())));
        $this->clearCookies();
        $this->insertHashToDB($this->getUserIdByLogin($login), $sid);
        setcookie("hash", $sid);


    }

    public function createSession($login, $password)
    {
        if (!$this->isAuthorized($login)) {
            if (!$this->isAvailableSessionByName("sess_" . $login) == false) {
                //echo "not available</br>";
                $this->clearSession($login);
                $this->clearCookies();

                $sessid = md5(crypt($password . md5($login . time())));

                session_id($sessid);
                session_name("sess_" . $login);
                session_start();
                $_SESSION['phpsessid'] = $sessid;
                $_SESSION['enabled'] = false;
                $_SESSION['color'] = 'blue';

                $id = $this->getUserIdByLogin($login);

                $this->insertHashToDB($id, $sessid);
                //echo "from create cookie:</br>";
                setcookie("sess_" . $login, $sessid);
                //var_dump($_COOKIE);
                //echo "from create phpsession:</br>";
               // var_dump(session_name());
               // var_dump(session_id());
                //var_dump($_SESSION);
                //echo "end from create</br>";
                return $sessid;
            }
        }
    }

    public function clearCookies()
    {
        $str = "";
        foreach ($_COOKIE as $name => $value)
        {
            if (setcookie($name, '', date('U') - 3600 * 24)) {
                $str .= "$name - ok <br>";
            } else {
                $str .= "$name - fuuuu <br>";
            }
        }
        //  echo $str;
    }

    public function getSessionIdByLogin($login)
    {
        $pdo = $this->dataModule->getConnection();
        $sql = "SELECT `hash` from `dzundza_account` where login = :login";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':login', $login, PDO::PARAM_STR);
        $stn->execute();
        $result = $stn->fetch(PDO::FETCH_ASSOC);
        return $result['hash'];
    }

    public function   getHash($login)
    {
        $pdo = $this->dataModule->getConnection();
        $sql = "SELECT `hash` from `dzundza_account` where login = :login";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':login', $login, PDO::PARAM_STR);
        $stn->execute();
        $result = $stn->fetch(PDO::FETCH_ASSOC);
        return $result['hash'];

    }

    public function getUserIdByLogin($login)
    {
        $pdo = $this->dataModule->getConnection();
        $sql = "SELECT idaccount from `dzundza_account` where login = :login";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':login', $login, PDO::PARAM_STR);
        $stn->execute();
        $result = $stn->fetch(PDO::FETCH_ASSOC);
        return $result['idaccount'];


    }

    public function checkHash($login, $hashPassword)
    {
        $ishash = false;
        $pdo = $this->dataModule->getConnection();
        $sql = "SELECT `hash` from `dzundza_account`  WHERE `login`=:login";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':login', $login, PDO::PARAM_STR);
        $result = $stn->execute();
        $res = $stn->fetch(PDO::FETCH_ASSOC);
        if ($res != null) {
            if ($hashPassword == $res['hash']) {
                $ishash = true;
            }
        }

       // if (!$result) var_dump($stn->errorInfo());
        // var_dump($result);
        return $ishash;


    }

    public function insertHashToDB($idUser, $hash)
    {
        $pdo = $this->dataModule->getConnection();
        $sql = "UPDATE `dzundza_account` SET `hash`=:hash  WHERE `idaccount`=:id";
        $stn = $pdo->prepare($sql);
        $stn->bindParam(':hash', $hash, PDO::PARAM_STR);
        $stn->bindParam(':id', $idUser, PDO::PARAM_INT);
        $result = $stn->execute();
      //  if (!$result) var_dump($stn->errorInfo());
        // var_dump($result);

    }

    public function isAuthorized($login)
    {


    }

    public function getCurrentSession()
    {
        return session_name();

    }

    public function isAvailableSessionByName($sessionName)
    {
        if ($this->getCurrentSession() == $sessionName) {
            return true;
        }
        return false;

    }


    public function echoCookie()
    {
        //  echo "COOKIE</br>";
        //var_dump($_COOKIE);
    }
}
